package com.lky.marshallmall.marshall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.lky.common.constant.AuthServerConstant;
import com.lky.common.utils.R;
import com.lky.common.vo.MemberVo;
import com.lky.marshallmall.marshall.auth.feign.MemberFeignService;
import com.lky.marshallmall.marshall.auth.utils.HttpUtils;
import com.lky.marshallmall.marshall.auth.vo.TokenVo;
import com.lky.marshallmall.marshall.auth.vo.WeiboTokenVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by
 * autor : Marshall lky
 * datetime: 2021/5/26 13:53
 * 处理社交登录请求
 */
@Controller
@Slf4j
@RequestMapping("oauth2.0")
public class OAuth2Controller {

    @Autowired
    private MemberFeignService memberFeignService;

    @GetMapping("/weixin/success")
    public String weixin(String code, HttpSession session) throws Exception {
        //根据code换取accesstoken，登陆成功跳转首页
        Map<String, String> map = new HashMap<>();
        map.put("appid", "wx79653742c2ef0b9d");
        map.put("secret", "f59938bdaa598dc6a30c84f2730fbc8f");
        map.put("code", code);
        map.put("grant_type", "authorization_code");
        //获取token
        HttpResponse response = HttpUtils.doGet("https://api.weixin.qq.com", "/sns/oauth2/access_token", "get", null, map);
        //处理token
        if (response.getStatusLine().getStatusCode() == 200) {
            //获取到了token
            String json = EntityUtils.toString(response.getEntity());
            TokenVo tokenVo = JSON.parseObject(json, TokenVo.class);
            //拿到当前社交用户需要自动注册，为当前社交用户关联一个会员信息账号，以后这个账号对应指定的会员
            //登录或注册该用户
            R<MemberVo> outhLogin = memberFeignService.oauthLogin(tokenVo);
            if (outhLogin.getCode() == 0) {

                MemberVo data = outhLogin.getData(new TypeReference<MemberVo>() {
                });
                System.out.println("用户信息" + data);
                log.info("登陆成功，用户：{}", data);
                session.setAttribute("loginUser", data);
                //成功回首页
                return "redirect:http://marshallmall.com";
            }

            return "redirect:http://auth.marshallmall.com/login.html";
        } else {
            return "redirect:http://auth.marshallmall.com/login.html";
        }
    }

    @GetMapping("/weibo/success")
    public String weibo(@RequestParam("code") String code,HttpSession session) throws Exception {
        Map<String, String> map = new HashMap<>();
        map.put("client_id", "2782236512");
        map.put("client_secret", "1fe75b1b30a2143e1a3f513a46d312fb");
        map.put("grant_type", "authorization_code");
        map.put("redirect_uri", "http://auth.marshallmall.com/oauth2.0/weibo/success");
        map.put("code", code);
        //获取token
        HttpResponse response = HttpUtils.doPost("https://api.weibo.com", "/oauth2/access_token", "post", null, null, map);
        //处理token
        if (response.getStatusLine().getStatusCode() == 200) {
            String json = EntityUtils.toString(response.getEntity());
            WeiboTokenVo weiboTokenVo = JSON.parseObject(json, WeiboTokenVo.class);
            R<MemberVo> memberVoR = memberFeignService.oauthLogin(weiboTokenVo);
            if (memberVoR.getCode() != 0){
                return "redirect:http://auth.marshallmall.com/login.html";
            }
            MemberVo data = memberVoR.getData(new TypeReference<MemberVo>(){});
            System.out.println("用户信息" + data);
            log.info("登陆成功，用户：{}", data);
            //todo 默认的令牌，作用域是当前域，需要解决子域session共享问题  并且使用json序列化方式序列化到redis中
            session.setAttribute(AuthServerConstant.SESSION_NAME,data);
            //成功回首页
            return "redirect:http://marshallmall.com";
        }
        //失败回登录页
        return "redirect:http://auth.marshallmall.com/login.html";
    }

}
